<template>
  <a-modal
    :title="props.formType != 'add' ? '公司业务员信息修改' : '新增公司业务员'"
    v-model:open="visibleFlag"
    :maskClosable="false"
    @cancel="handleCancel"
    :width="800"
    style="font-size: 18px"
  >
    <div class="basic-info-section">
      <a-row :gutter="24" v-if="props.formType != 'add'">
        <a-col :span="12">
          <div class="form-item-label">
            <span>登录账号：{{ props.rowData.no }}</span>
          </div>
        </a-col>
        <a-col :span="12">
          <div class="form-item-label">
            <span>{{ props.rowData.departName }}：{{ props.rowData.name }}</span>
          </div>
        </a-col>
      </a-row>
      <group-title :iconOptions="{ class: 'text-blue-600' }">基础信息</group-title>
      <a-form ref="formRef" :model="formData" :rules="rules" :label-col="{ span: 8 }">
        <a-row :gutter="16">
          <!-- 第一行 -->
          <template v-if="props.formType == 'add'">
            <a-col :span="12">
              <a-form-item label="部门:" name="departId">
                <a-tree-select
                  v-model:value="formData.departId"
                  :treeData="treeData"
                  :fieldNames="{ label: 'name', key: 'id', value: 'id' }"
                  placeholder="请选择部门"
                  allow-clear
                  tree-default-expand-all
                />
                <!-- <CustomSelect
                v-model:value="formData.departName"
                :placeholder="'请选择部门'"
                :api="departApi.list"
                :queryParams="departParams"
                queryParamKey="nameLeftLike"
                :response-adapter="filterDepartParams"
              /> -->
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="姓名:" name="id">
                <CustomSelect
                  v-model:value="formData.id"
                  :placeholder="'请选择姓名'"
                  :api="userApi.page"
                  :queryParams="userParams"
                  :initParams="{ id: formData.id }"
                  queryParamKey="nameLeftLike"
                  :response-adapter="filterUserParams"
                  labelField="name,no"
                />
              </a-form-item>
            </a-col>
          </template>

          <!-- 第二行 -->
          <a-col :span="12">
            <a-form-item label="授权业务:" name="authBussType">
              <a-select v-model:value="formData.authBussType" placeholder="请选择" :options="OPERATION_SALESMAN_AUTH_BUSS_TYPE" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="状态:" name="status">
              <a-select v-model:value="formData.status" placeholder="请选择" :options="SALESMAN_STATUS" />
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item label="岗位:" name="position">
              <a-select v-model:value="formData.position" placeholder="请选择" :options="SALESMAN_POST" />
            </a-form-item>
          </a-col>
          <a-col :span="12" v-if="formData.position == 1">
            <a-form-item label="主管:" name="supervisorId">
              <CustomSelect
                v-model:value="formData.supervisorId"
                :placeholder="'请选择主管'"
                :api="exhibitionApi.queryPage"
                :initParams="{ id: formData.supervisorId }"
                :queryParams="{ position: 0 }"
                queryParamKey="name"
                labelField="name,no"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <template #footer>
      <a-space>
        <a-button @click="handleReset">重置</a-button>
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<script setup>
  import { ref, reactive, watch, onMounted, computed } from 'vue'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  import { message } from 'ant-design-vue'
  import { userApi } from '/@/api/system/b-operation/user-api'
  import { exhibitionApi } from '/@/api/business/b-operation/exhibition/exhibition-api'
  import CustomSelect from '/@/components/business/comment/CustomSelect.vue'
  import { ZZB_ENABLE_STATUS_ENUM } from '/@/constants/system/system-const.js' // 根据实际路径调整
  import {
    SALESMAN_POST, // 岗位
    OPERATION_SALESMAN_AUTH_BUSS_TYPE, // 授权业务
    SALESMAN_STATUS, // 业务员状态
  } from '/@/constants/dict'

  import useCommonStore from '/@/store/modules/common'

  const props = defineProps({
    open: {
      type: Boolean,
      default: false,
      required: true,
    },

    // 表单类型 add/update/view
    // add: 新增, update: 编辑,view: 查看
    formType: {
      type: String,
      default: 'add',
    },
    rowData: {
      type: Object,
      default: () => {
        return null
      },
    },
  })
  const emit = defineEmits(['update:open', 'ok'])
  // 是否显示
  const visibleFlag = computed({ get: () => props.open, set: (val) => emit('update:open', val) })

  const treeData = ref([])

  const submitLoading = ref(false)
  const formRef = ref()

  const rules = ref({
    departId: [{ required: true, message: '请选择部门' }],
    id: [{ required: true, message: '请选择姓名' }],
    authBussType: [{ required: true, message: '请选择授权业务' }],
    status: [{ required: true, message: '请选择状态' }],
    position: [{ required: true, message: '请选择岗位' }],
    supervisorId: [{ required: true, message: '请选择主管' }],
  })

  async function getFrom(data) {
    try {
      SmartLoading.show()
      if (data) {
        const params = {
          id: data.id,
        }
        const queryResult = await exhibitionApi.findOne(params)
        formData.value = queryResult.data
      }
    } finally {
      SmartLoading.hide()
    }
  }

  const handleReset = () => {
    // 1.重置表单验证状态（不重置数据）
    formRef.value?.resetFields()

    // 2.仅重置非ID字段（解构排除id）
    const { id, ...resettableData } = formDefault
    Object.assign(formData.value, resettableData)
  }

  // 取消
  const handleCancel = () => {
    visibleFlag.value = false
    handleReset()
    Object.assign(formData.value, formDefault)
  }

  const formDefault = {
    no: undefined,
    id: undefined,
    departName: undefined,
    departId: undefined,
    name: undefined,
    position: undefined,
    supervisorId: undefined,
    authBussType: undefined,
    status: undefined,
  }
  let formData = ref({ ...formDefault })

  const save = () => {
    formRef.value?.validate().then(async () => {
      submitLoading.value = true
      let param = { ...formData.value }
      try {
        // 这里调用API保存数据
        if (props.formType == 'update') {
          await exhibitionApi.update(param)
        } else {
          await exhibitionApi.insert(param)
        }
        message.success('保存成功')
        emit('ok')
        handleCancel()
      } catch (error) {
        console.log(error)

        message.error('保存失败')
      } finally {
        submitLoading.value = false
      }
    })
  }

  // 点击确定，验证表单
  async function onSubmit() {
    try {
      await formRef.value.validateFields()
      save()
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!')
    }
  }

  const userParams = computed(() => {
    return {
      showRoleFlag: false,
      oDepartId: formData.value.departId === undefined ? undefined : formData.value.departId, // 根据部门ID查询用户
    }
  })
  const filterUserParams = (val) => {
    val.data?.forEach((element, index, arr) => {
      arr[index].disabled = element.status === ZZB_ENABLE_STATUS_ENUM.DISABLE_STATUS.value
    })
    return val
  }

  watch(
    [() => props.rowData, () => props.open],
    (newVal) => {
      console.log(props.formType)

      if ((props.formType == 'update' || props.formType == 'view') && props.open) {
        console.log('newVal===>', newVal[0])

        getFrom(newVal[0])
        // console.log('data===>', data.value)
      }
    },
    { deep: true, immediate: true },
  )

  onMounted(async () => {
    treeData.value = await useCommonStore().getDeptTreeAgent()
  })
</script>

<style lang="less" scoped>
  .basic-info-section {
    padding: 0 24px;

    .section-title {
      font-size: 16px;
      color: #1890ff;
      margin-bottom: 24px;
      padding-left: 12px;
      position: relative;
      font-weight: 500;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 14px;
        background: #1890ff;
        border-radius: 2px;
      }
    }
  }

  .form-item-label {
    padding: 8px 20px;
    font-weight: 500;
  }

  :deep(.ant-form-item) {
    margin-bottom: 24px; // 增加表单项间距

    .ant-form-item-label > label {
      color: rgba(0, 0, 0, 0.85); // 加深标签颜色
    }

    .ant-select-selector,
    .ant-input {
      border-radius: 4px; // 统一输入框圆角
    }
  }
  :deep(.ant-select-arrow) {
    right: 11px;
  }
</style>
